package com.travel.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import cn.hutool.crypto.digest.MD5;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Base64;
import java.util.UUID;

@Component
public class Base64ToImgNew {

    @Value("${img.save-path}")
    private String savePath;

    @Value("${img.base-url}")
    private String baseUrl;


    /**
     *
     * @param richtext 富文本
     * @description 将富文本<img>标签中的base64保存到本地并为下一步写入数据库做准备
     * @return String 处理后的富文本
     */
    public String richtextBase64ToImg(String richtext) {
        Document doc = Jsoup.parse(richtext);

        Elements body = doc.select("body");

        Elements imgs = body.select("img");

        for (Element img : imgs) {
            String base64 = img.attr("src");
            if (!base64.contains("data:image/")) continue;
            base64 = base64.substring(base64.indexOf(",",1) + 1);
            Base64.Decoder decoder = Base64.getDecoder();
            byte[] imgBytes = decoder.decode(base64);
            for ( byte b : imgBytes) {
                b = (byte) (b & 0xFF);
            }
            String fileName = MD5.create().digestHex(UUID.randomUUID().toString());
            String sb = savePath + "/" + fileName + ".png";
            String href_url = baseUrl + (baseUrl.endsWith("/") ? "" : "/") + fileName + ".png";
            img.attr("src",href_url);
            img.attr("alt", fileName + ".png");
            img.attr("style","max-width:100%;height:auto");
            img.removeAttr("data-href");
            try(OutputStream out = new FileOutputStream(sb)) {
                out.write(imgBytes);
                out.flush();
            }catch (IOException e){
                throw new RuntimeException(e);
            }
        }
        return body.toString().replaceAll("<body>","").replaceAll("</body>","");
    }

    /**
     *
     * @param base64  base64编码
     * @return 返回静态资源路由
     */
    public  String base64ToImgHerf(String base64) throws Exception {
        if (!base64.contains("data:image/")) return null;
        base64 = base64.substring(base64.indexOf(",",1) + 1);
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] imgBytes = decoder.decode(base64);
        for ( byte b : imgBytes) {
            b = (byte) (b & 0xFF);
        }
        String fileName = MD5.create().digestHex(UUID.randomUUID().toString());
        String sb = savePath + "/" + fileName + ".png";
        String href_url = baseUrl + fileName + ".png";
        try(OutputStream out = new FileOutputStream(sb)){
            out.write(imgBytes);
            out.flush();
        }catch (IOException e){
            throw new Exception(e.getMessage());
        }

        return href_url;
    }

}
